package com.github.dbutil;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**
 * <p>动态数据源管理工具</p>
 * @author  Crab2Died
 */
public class DBContextHolder {

    private static Logger logger = Logger.getLogger(DBContextHolder.class);

    /**
     *  ThreadLocal 数据源标识码
     */
    private static ThreadLocal<String> contextHolder = new ThreadLocal<>();

    /**
     * <p>获取线程内数据源</p>
     * @author  Crab2Died
     *
     * @return String 数据源标识码
     */
    static
    protected String getDSType() {
        return contextHolder.get();
    }

    /**
     * <p>设置当前线程数据源</p>
     * @author  Crab2Died
     *
     * @param str 数据源标识码
     * @return boolean   操作结果
     */
    static
    public boolean setDSType(String str) {
        try {
            clearDBType();
            if (StringUtils.isNotEmpty(str)) {
                contextHolder.set(str);
                logger.info("change data source [" + str + "] success!");
                return true;
            } else {
                logger.info("change data source [" + str + "] failed!");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("change data source [" + str + "] exception!", e);
            return false;
        }
    }

    /**
     * <p>移除当前线程的数据源</p>
     * @author  Crab2Died
     */
    static
    public void clearDBType() {
        contextHolder.remove();
    }

}
